class Storage {
  public key: string = '';
  public value: string[] = [];
  public position: number = 0;
  public storage: Object = {};
  private lStorageKey: string = 'commandHistory';
  private maxLimitSize: number = 100; // 记录栈最大保存长度
  constructor(argKey: string, argValue: string[] | []) {
    if (!argKey) {
      console.warn('请键入本终端的名称！');
      return;
    }
    this.key = argKey;
    this.value = argValue;
    // localStorage：终端命令行历史记录栈空值注入
    this.emptyValueInject();
  }
  /**
   * 将终端记录存入storage中，并且赋值到localStorage中
   */
  saveStorage() {
    const lStorage = JSON.parse(localStorage.getItem(this.lStorageKey));
    this.storage = lStorage ?? {};
    if (!this.storage[this.key]) this.storage[this.key] = {};
    this.storage[this.key].stacks = this.value;
    this.storage[this.key].position = this.position;
    localStorage.setItem(this.lStorageKey, JSON.stringify(this.storage));
  }
  /**
   * localStorage：终端命令行历史记录栈空值注入
   */
  emptyValueInject() {
    const lStorage = JSON.parse(localStorage.getItem(this.lStorageKey));
    this.storage = lStorage ?? {};
    if (Object.keys(this.storage).length && this.storage[this.key]) {
      this.value = this.storage[this.key].stacks;
      // 设置为最后一位，以便于刷新后直接取最后一位索引值
      this.position = this.storage[this.key].stacks.length;
    }
  }
  /**
   * 新增命令行记录
   * @param command 命令
   */
  addCommand(command) {
    if (this.value.length >= this.maxLimitSize) return;
    this.value.push(command);
    // 新增命令行，直接将历史记录偏移至最后一个指针位置
    const maxLen = this.value.length;
    this.position = maxLen;
    this.saveStorage();
  }
  /**
   * 获取命令行记录
   * @param position 命令行对应的索引值
   */
  getCommand(searchPosition: number) {
    if (searchPosition === 1) {
      this.addPosition();
    } else {
      this.removePosition()
    }
    // 当历史记录栈里没有数据时，返回空字符
    const curCommand = this.value[this.position] ?? '';
    return curCommand;
  }
  /**
   * 移除某条命令行记录（暂时不用）
   * @param position 命令行对应的索引值
   */
  removeCommand(position) {
    this.value.splice(position, 1);
    const maxLen = this.value.length;
    this.position = maxLen;
    this.saveStorage();
  }
  /**
   * 移除所有命令行记录
   * @param position 命令行对应的索引值
   */
  clearCommand() {
    this.value = [];
    this.resetPosition();
  }
  /**
   * 获取当前命令行执行索引
   * @returns position
   */
  getPosition() {
    return this.position;
  }
  /**
   * 向后移动当前命令行执行索引
   */
  addPosition() {
    const maxLen = this.value.length;
    if (maxLen > this.position) {
      this.position++;
      this.saveStorage();
    }
  }
  /**
   * 向前移动当前命令行执行索引
   */
  removePosition() {
    if (this.position > 0) {
      this.position--;
      this.saveStorage();
    }
  }
  /**
   * 重置命令行对应索引
   */
  resetPosition() {
    this.position = 0;
    this.saveStorage();
  }
}

export default Storage;
